import json
from typing import Any
from django.http import JsonResponse
from django.core.handlers.wsgi import WSGIRequest
from django.db import transaction
from django.core.cache import cache
from django.conf import settings

from rest_framework.parsers import JSONParser
from rest_framework import status


from . import models
from . import wx_api

import requests

from app_common import app_except


import logging

logger = logging.getLogger("log")


def unifiedorder(
    request,
    total_fee,
    order_title,
    call_back_url,
    score,
    shopping: models.StoreShopping,
    pay_for: models.WxUserPaymentRecord.PayFor,
    *args,
    **kwargs,
):
    """
    支付接口
    统一下单
    http://api.weixin.qq.com/_/pay/unifiedorder
    https://developers.weixin.qq.com/miniprogram/dev/wxcloudrun/src/development/pay/order/unified.html
    """
    if total_fee < 1:
        raise app_except.ValueErr

    openid = request.META.get("HTTP_X_WX_OPENID", None)
    if not openid:
        raise app_except.NullErr(msg="openid")

    spbill_create_ip = request.META.get("HTTP_X_FORWARDED_FOR", None)
    if not spbill_create_ip:
        raise app_except.NullErr(msg="spbill_create_ip")

    env_id = request.META.get("HTTP_X_WX_ENV", None)
    if not env_id:
        raise app_except.NullErr(msg="env_id")

    mch_id = settings.MCH_ID
    if not mch_id:
        raise app_except.NullErr(msg="mch_id")

    service = request.META.get("HTTP_X_WX_SERVICE", None)
    if not service:
        raise app_except.NullErr(msg="service")

    wxuser: models.WxUser = request.user
    paymentRecord = models.WxUserPaymentRecord(
        user_uuid=wxuser.uuid,
        total_fee=total_fee,
        openid=openid,
        order_title=order_title,
        spbill_create_ip=spbill_create_ip,
        mch_id=mch_id,
        env_id=env_id,
        service=service,
        score=score,
        pay_for=pay_for,
    )
    paymentRecord.save()
    if shopping:
        shopping.payment_record_uuid = paymentRecord.uuid
        shopping.save()

    out_trade_no = paymentRecord.out_trade_no
    params = {
        "body": order_title,
        "openid": openid,
        "out_trade_no": out_trade_no,
        "spbill_create_ip": spbill_create_ip,
        "env_id": env_id,
        "sub_mch_id": mch_id,
        "total_fee": total_fee,
        "callback_type": 2,
        "container": {"service": service, "path": call_back_url},
    }

    res = requests.post(
        url=f"{wx_api.unifiedorder}",
        json=params,
        headers={
            "Content-Type": "application/json",
        },
        timeout=10,
    )

    d = json.loads(res.content)

    logger.info(f"response content: {res.content}")
    logger.info(f"req params: {params}")
    logger.info(f"req params: {d}")

    if d["errcode"] != 0:
        raise app_except.ValueErr(msg=d["errcode"])

    return d, paymentRecord.out_trade_no


def queryorder(request, *args, **kwargs):
    """
    查询订单	http://api.weixin.qq.com/_/pay/queryorder
    """
    return False


def closeorder(request, *args, **kwargs):
    """
    关闭订单	http://api.weixin.qq.com/_/pay/closeorder
    """
    return False


def downloadbill(request, *args, **kwargs):
    """
    下载对账单	http://api.weixin.qq.com/_/pay/downloadbill
    """
    return False


def refund(request, *args, **kwargs):
    """
    申请退款	http://api.weixin.qq.com/_/pay/refund
    """
    return False


def queryrefund(request, *args, **kwargs):
    """
    查询退款	http://api.weixin.qq.com/_/pay/queryrefund
    """
    return False
